package cn.sgy.infrastructure.web.initialize.business;

import cn.hutool.core.util.StrUtil;
import cn.sgy.infrastructure.web.initialize.config.WenInitAutoConfiguration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

/**
 * @author sgy
 * @description 通过 {@link InitializeDispatcherServletController} 初始化 DispatcherServlet
 * @date 2023-03-08
 */
@Slf4j
@RequiredArgsConstructor
public class InitializeDispatcherServletHandler implements CommandLineRunner {
    private final RestTemplate restTemplate;
    private final ConfigurableEnvironment configurableEnvironment;

    @Override
    public void run(String... args) throws Exception {
        try {
            restTemplate.execute(getUrl(), HttpMethod.GET, null, null);
        } catch (Throwable t) {
            log.error("web基础设施预热访问失败，异常如下：", t);
        }
    }

    /**
     * 根据端口号和servlet.context-path拼接预热的地址
     *
     * @return
     */
    private String getUrl() {
        // 获取项目路径，如果没有则用空字符串
        String contextPath = configurableEnvironment.getProperty("server.servlet.context-path", "");
        // 如果contextPath不是空字符串并且结尾是/则把这个去掉
        if (StrUtil.isNotBlank(contextPath) && contextPath.endsWith("/")) {
            contextPath = contextPath.substring(0, contextPath.length() - 1);
        }
        // 获取端口号，如果没有则就是默认的8080
        String port = configurableEnvironment.getProperty("server.port", "8080");
        return StrUtil.format("http://127.0.0.1:{}{}{}",port,contextPath, WenInitAutoConfiguration.INITIALIZE_PATH);
    }
}
